package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sobremesa
 * @version 1.0.0
 * @ClassName LybApplicationContext.java
 * @Description 这是一个自定义的ApplicationContext，用来实现spring
 * @createTime 2021年08月16日 11:23:00
 */
public class LybApplicationContext {
    private Class configClass;

    private  ConcurrentHashMap<String,Object> singltonObjects = new ConcurrentHashMap<>();  //单例池
    private  ConcurrentHashMap<String,BeanDefinition> beanDefinitionHashMap = new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorsList = new ArrayList<>();

    /**
     *
     * @param configClass   从前面获取到类名
     */
    public LybApplicationContext(Class configClass){
        this.configClass = configClass;

        //进行解析配置类
        //ComponentScan注解---> 扫描路径 ---> 扫描---->BeanDefinition---------->BeanDefinitionMap
        scan(configClass);

        for (Map.Entry<String, BeanDefinition> entry: beanDefinitionHashMap.entrySet()){
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName,beanDefinition);
                singltonObjects.put(beanName,bean);
            }
        }


    }

    public Object createBean(String beanName, BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getClazz();
        try {
            //实例化一个对象
            Object instance = clazz.getDeclaredConstructor().newInstance();

            //对属性进行赋值  依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {

                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);


                }
            }
            //Aware回调
            //如果实现BeanNameAware接口
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            //初始化前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance  = beanPostProcessor.postProcessorBeforeInitialization(instance, beanName);
            }

            //初始化
            if (instance instanceof InitializingBean) {
                try {
                    ((InitializingBean) instance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //初始化后
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance = beanPostProcessor.postProcessorAfterInitialization(instance,beanName);
            }
            //BeanPostProcessor



            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;

    }


    private void scan(Class configClass) {
        ComponentScan componentScanAnnotations = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotations.value(); //扫描路径
        // System.out.println(path);   //com.lyb.service
        path = path.replace(".","/");
        //扫描
        //类加载器:Bootstrap(根加载器)--->jre/lib、 Ext(扩展加载器)--->jre/ext/lib 、 App(应用加载器)------->classpath---->
        ClassLoader classLoader = LybApplicationContext.class.getClassLoader(); //app
        // URL resource = classLoader.getResource("com/lyb/service");
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());

        if (file.isDirectory()) {

            File[] files = file.listFiles();
            for (File f: files) {
                //System.out.println(f);
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = f.getAbsolutePath().substring(fileName.indexOf("com"),fileName.indexOf(".class"));
                    className = className.replace("\\",".");
                    //System.out.println(className);

                    try {

                        Class<?> clazz = classLoader.loadClass(className);
                        if (clazz.isAnnotationPresent(Component.class)) {
                            //表示当前这个类是一个Bean
                            //解析类，判断当前bean是单例bean还是prototype bean

                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorsList.add(instance);
                            }

                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beaName = componentAnnotation.value();

                            //bean 的定义
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if (clazz.isAnnotationPresent(Scope.class)) {
                                Scope scopedAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopedAnnotation.value());
                            }else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionHashMap.put(beaName,beanDefinition);


                        }

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
    }

    public Object getBean(String beanName){
        if(beanDefinitionHashMap.containsKey(beanName)){
            BeanDefinition beanDefinition = beanDefinitionHashMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object o = singltonObjects.get(beanName);
                return o;
            }else {
                //非单例对象
                Object bean = createBean(beanName,beanDefinition);
                return bean;
            }

        }else {
            //不存在对应的bean
            throw new NullPointerException();
        }
    }
}
